<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Now!Chat &rsaquo; Install</title>
    <link rel="stylesheet" href="install.css" type="text/css" />
    <link rel="stylesheet" href="../admin/css/admin.css" type="text/css" />
</head>
<body>
<div id="error-page">
<?php

require_once("../config.php");
require_once("../includes/common/dbclass.php");
require_once("../includes/common/ServiceFactory.php");

Session::start();

global $db;
$config = ServiceFactory::get("SystemConfiguration");
$userService = ServiceFactory::get("UserService");
$referer = $_SERVER['PHP_SELF'];

if(file_exists("./ncinstalled.$$$"))
{
    unlink("./ncinstalled.$$$");
    echo '<p>setup done! <br /><br /><a href="../">Go to Home</a></p>';
    exit();
}
elseif (isset($_POST['setup']))
{
    $newAvatarPath = $_POST['avatar-path'];
    $siteTitle = $_POST['site-title'];
    $siteUrl = $_POST['site-url'];
    $emoticonPath = $_POST['emoticon-path'];
    $pass = $_POST['pass'];
    $pass1 = $_POST['pass1'];
    
    try
    {
        if(empty($pass))
        {
            RedirectMessage::info("Bạn chưa nhập mật khẩu", "Error");
        }
        elseif($pass != $pass1)
            RedirectMessage::info("Mật khẩu nhập không giống nhau", "Error");
        elseif(!Validator::validate($pass, "password"))
            RedirectMessage::info("Mật khẩu không hợp lệ, mật khẩu chỉ chứa các chữ cái và số", "Error");
        else
        {
            resetDatabase($db, DB_NAME);
            runSqlScript($db);
            
            createAdminUser($us);
            
            if(isset($_POST['install-sample-data']) && !empty($_POST['install-sample-data']))
            {
                insertSampleData($us);
            }
            
            $admin = $userService -> findUserByName("admin");
            $admin -> setPassword(sha1($pass));
            $userService -> updateUser($admin);
            
            $config -> updateSetting("avatar-path", $newAvatarPath);
            $config -> updateSetting("site-url", $siteUrl);
            $config -> updateSetting("site-title", $siteTitle);
            $config -> updateSetting("emoticon-path", $emoticonPath);
            
            fclose(fopen("./ncinstalled.$$$", "w"));
        }
    } 
    catch(Exception $ex)
    {
        RedirectMessage::info($ex -> getMessage(), "Error");
    }

    Response::redirect($referer);
}
else
{
    $schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
    $guessurl = preg_replace('|/setup/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
?>
<form action="<?php echo $referer; ?>" method="post">
<?php
    if(RedirectMessage::hasMessage())
    {
        InfoArea::showInfo(RedirectMessage::getMessage(), RedirectMessage::getMessage('title'), RedirectMessage::getMessage('type'));
        RedirectMessage::removeMessage();
    }
?>
<h2>Cài đặt Now!chat</h2>
<p>Bạn có thể sử dụng các giá trị mặc định, hoặc thay đổi theo ý mình</h2></p>
<p>
    <label for='site-title'>Site title</label>
    <input type='text' name='site-title' id='site-title' size='45' value='Now!chat online'/>
    <small>Title hiển thị</small>
</p>
<p>
    <label for='site-url'>Site address(URL)</label>
    <input type='text' name='site-url' id='site-url' size='45' value='<?php echo $guessurl; ?>'/>
    <small>Nhập vào địa chỉ của site nếu địa chỉ này không đúng với thư mục cài</small>
<p>
    <label for='avatar-path'>Thư mục Avatar</label>
    <input type='text' name='avatar-path' id='avatar-path' size='40' value='images/avatars'/>
    <small>Thư mục chứa các avatars của user</small>
</p>
<p>
    <label for='emoticon-path'>Thư mục Emoticon</label>
    <input type='text' name='emoticon-path' id='emoticon-path' size='40' value='images/emoticons'/>
    <small>Thư mục chứa các smiley</small>
</p>

<h2>Install sample data</h2>
<p>
    <label>&nbsp;</label>
    <label class='Normal' for='install-sample-data'>
        <input type='checkbox' name='install-sample-data' id='install-sample-data' checked="checked" />
        Cài đặt dữ liệu mẫu
    </label>
    <small class="Right">Chọn Cài đặt dữ liệu mẫu để cài các dữ liệu mẫu</small>
</p>
<h2>Select administrator password</h2>
<p>
    <label for='pass'>Admin password</label>
    <input type='password' name='pass' id='pass' size="16" maxlength="16"/>
    <small class="Right">Chọn mật khẩu admin, tên tài khoản admin mặc định là admin</small>
    <label for='pass1'>Retype password</label>
    <input type='password' name='pass1' id='pass1' size="16" maxlength="16"/>
    <small class="Right">Nhập lại mật khẩu</small>
</p>
<p>
    <div class="Holder">
        <input class="Button" type="submit" name="setup" value="Next >>" />
    </div>
</p>
</form>
<?php 
}

function resetDatabase($db, $dbName)
{
    dropTables($db, $dbName);
}

function dropTables($db, $dbName)
{
    dropFK($db);
    $tables = $db -> getResults("SHOW TABLES FROM $dbName", ARRAY_N);
    
    if(count($tables))
    foreach ($tables as $table)
    {
        $db -> query("DROP TABLE IF EXISTS `$table[0]`");
    }
}

function dropFK($db)
{
    $fks = $db -> getResults("SELECT ke.table_name, ke.constraint_name FROM information_schema.KEY_COLUMN_USAGE ke WHERE ke.referenced_table_name IS NOT NULL ORDER BY ke.table_name;");
    if(count($fks))
    foreach ($fks as $fk)
    {
        $db -> query("alter table {$fk -> table_name} drop foreign key {$fk -> constraint_name};");
    }
}

function runSqlScript( &$database, $sqlfile = 'nowchat.sql') {
    
    $file = '../data/' . $sqlfile;
    if(!file_exists($file))
        throw new Exception("Không tìm thấy file $sqlfile");
    
    $mqr = @get_magic_quotes_runtime();
    @set_magic_quotes_runtime(0);
    $query = fread( fopen( $file, 'r' ), filesize( $file ) );
    @set_magic_quotes_runtime($mqr);
    $pieces  = splitSql($query);

    for ($i = 0; $i < count($pieces); $i++) {
        $pieces[$i] = trim($pieces[$i]);
        if(!empty($pieces[$i]) && $pieces[$i] != "#") {
            $database -> query( $pieces[$i] );
        }
    }
}

function splitSql($sql) {
    $sql = trim($sql);

    $buffer = array();
    $ret = array();
    $in_string = false;

    for($i = 0; $i < strlen($sql) - 1; $i++) {
        if($sql[$i] == ";" && !$in_string) {
            $ret[] = substr($sql, 0, $i);
            $sql = substr($sql, $i + 1);
            $i = 0;
        }
        if($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\") {
            $in_string = false;
        }
        elseif(!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\")) {
            $in_string = $sql[$i];
        }
        if(isset($buffer[1])) {
            $buffer[0] = $buffer[1];
        }
        $buffer[1] = $sql[$i];
    }

    if(!empty($sql)) {
        $ret[] = $sql;
    }
    return($ret);
}

function createAdminUser($userService)
{
    $user = new Account("admin", "admin", "dung.nguyen@evolus.vn", "1986/10/10", "Code", "Block", "64/5B Phan Xich Long, P3, Q.PN");
    $userService -> createUser($user);
    $userService -> setUserRole($userService -> findUserByName("admin") -> getID(), ServiceFactory::get() -> getRoleByName("Administrator"));
}

function insertSampleData($userService)
{
    $userService -> createUser(new Account("phdieuli", "123456", "phdieuli@gmail.com", "1987/04/19", "Linh", "Pham Thi Dieu", "928 duong 30/4 tp Vung Tau", "0955258210"));
    $userService -> createUser(new Account("lvxung", "123456", "xunglv@gmail.com", "1987/04/06", "Xung", "Le Van", "123 Le Hong Phong tp.Vung Tau", "0955123875"));
    $userService -> createUser(new Account("ttdat", "123456", "ttdat@gmail.com", "1987/04/06", "Dat", "Truong Tien", "123 Le Hong Phong tp.Vung Tau", "0955123875"));
    $userService -> createUser(new Account("ltmlinh", "123456", "ltmlinh@gmail.com", "1987/06/26", "Linh", "Le Thi My", "523 Tran Hung Dao Q1 TP.Ho Chi Minh", "0909243445"));
    $userService -> createUser(new Account("ttlan", "123456", "ttlan@gmail.com", "1987/05/03", "Lan", "Tao Thuy", "34 Nguyen Thai Hoc TP. Vung Tau", "0903857836"));
    $userService -> createUser(new Account("ptgminh", "123456", "ptgminh@gmail.com", "1980/02/06", "Minh", "Pham Thi Gia", "145 Tran Hung Dao Q1 TP. Ho Chi Minh", "0909346874"));
    $userService -> createUser(new Account("ttha", "123456", "ttha@gmail.com", "1987/07/12", "Ha", "Trieu Thi", "156 Le Quy Don TP. Buon Me Thuot", "0909762473"));
    $userService -> createUser(new Account("nnanh", "123456", "nnanh@gmail.com", "1989/12/04", "Anh", "Nguyen Nguyet", "97 Bui Huu Nghia TP. Da Lat", "0909453765"));
    $userService -> createUser(new Account("lnhtien", "123456", "lnhtien@gmail.com", "1988/04/23", "Tien", "Le Nguyen Hoa", "76 Tran Hung Dao TP.Ho Chi Minh", "0909534872"));
    $userService -> createUser(new Account("tvkha", "123456", "tvkha@gmail.com", "1988/04/03", "Kha", "Tran Vuong", "98 Cong Quynh TP.Ho Chi Minh", "0980475937"));
    $userService -> createUser(new Account("plna", "123456", "plna@gmail.com", "1987/07/30", "Na", "Phan Le", "25 Nguyen Thi Minh Khai TP.Vung Tau", "0909435768"));
    $userService -> createUser(new Account("dhmnghia", "123456", "dhmnghia@yahoo.com", "1988/09/02", "Nghia", "Do Hoang Minh", "98 Nguyen Van Cu TP.Ho Chi Minh", "0987233473"));
    $userService -> createUser(new Account("tthang", "123456", "tthang@yahoo.com", "1986/09/03", "Hang", "Tran Thu", "98 Cach mang thang tam TP. Ho Chi Minh", "0987465862"));
    $userService -> createUser(new Account("tttanh", "123456", "tttanh@yahoo.com", "1987/09/23", "Anh", "Tran Thi Tram", "12 Nguyen Van Cu TP.Vung Tau", "0908473625"));
    $userService -> createUser(new Account("plnlong", "123456", "plnlong@yahoo.com", "1987/03/05", "Long", "Pham Le Ngoc", "24 Le Hong Phong TP.Vung Tau", "0987246583"));
    $userService -> createUser(new Account("nhthu", "123456", "nhthu@gmail.com", "1987/04/05", "Thu", "Nguyen Hoai", "98 Binh Gia TP. Kien Giang", "0973958736"));
    $userService -> createUser(new Account("ntnam", "123456", "ntnam@gmail.com", "1987/03/03", "nam", "nguyen thanh", "65 Ba Cu TP.Phan Thiet", "0987364826"));
    $userService -> createUser(new Account("pthmi", "123456", "pthmi@yahoo.com", "1987/04/04", "Mi", "Pham Thi Hoa", "34 Ly Tu Trong TP.Ha Noi", "0982648753"));
    $userService -> createUser(new Account("tlttuan", "123456", "tlttuan@yahoo.com", "1987/08/20", "Tuan", "Tran Le Thanh", "984 Nguyen Van Cu", "0973645274"));
    $userService -> createUser(new Account("tqhuy", "123456", "tqhuy@yahoo.com", "1987/09/02", "Huy", "Tran Quoc", "23 Hai Ba Trung TP. Ho Chi Minh", "0974657462"));
    $userService -> createUser(new Account("nkvuong", "123456", "nkvuong@gmail.com", "1983/08/04", "Vuong", "Nguyen Ky", "211 Phan Dang Luu", "0978264736"));
    $userService -> createUser(new Account("pdtu", "123456", "pdtu@yahoo.com", "1984/03/04", "Tu", "Pham Duy", "75 Ly Thuong Kiet TP.Da Lat", "0909756383"));
    $userService -> createUser(new Account("pdphung", "123456", "pdphung@gmail.com", "1989/06/07", "Hung", "Pham Duy Phuong", "98 Xa Lo Ha Noi TP.Ho Chi Minh", "0909065732"));
    
    $roleManger = ServiceFactory::get() -> getRoleByName("Manager");
    $userService -> setUserRole($userService -> findUserByName("phdieuli") -> getID(), $roleManger);
    $userService -> setUserRole($userService -> findUserByName("lvxung") -> getID(), $roleManger);
    $userService -> setUserRole($userService -> findUserByName("ttdat") -> getID(), $roleManger);
    
    
}

?>
</div>
<div style="clear:both;height:20px;"></div>
</body>
</html>